package com.xincheng.shuimalong.activity.management;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.DateUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.widget.pickerview.OptionsPickerView;
import com.xincheng.library.widget.pickerview.TimePickerView;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.IdCardCameraActivity;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.customer.Customer;
import com.xincheng.shuimalong.helper.AllCapTransformationMethod;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.ShowActivity;
import com.xincheng.shuimalong.util.UnitUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.net.ssl.X509KeyManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by 许浩 on 2017/7/1.
 */

public class AddManagerCarActivity extends BaseActivity {

    @BindView(R.id.identity_front)
    FrameLayout identityFront;
    @BindView(R.id.identity_front_tv)
    TextView identityFrontTv;
    @BindView(R.id.img_identity_front)
    ImageView imgIdentityFront;
    @BindView(R.id.img_identity_front_clear)
    ImageView imgIdentityFrontClear;
    @BindView(R.id.identity_contrary)
    FrameLayout identityContrary;
    @BindView(R.id.identity_contrary_tv)
    TextView identityContraryTv;
    @BindView(R.id.img_identity_contrary)
    ImageView imgIdentityContrary;
    @BindView(R.id.img_identity_contrary_clear)
    ImageView imgIndentityContraryClear;
    @BindView(R.id.et_car_number)
    EditText etCarNumber;
    @BindView(R.id.et_car_vin)
    EditText etVin;
    @BindView(R.id.tv_car_date)
    TextView tvCarDate;
    @BindView(R.id.btn_next)
    StateButton btnNext;
    @BindView(R.id.switch_year)
    SwitchCompat switchYear;
    @BindView(R.id.switch_car_new)
    SwitchCompat switchCarNew;
    @BindView(R.id.car_type_rg)
    RadioGroup rgCartype;
    @BindView(R.id.policy_usage_rg)
    RadioGroup rgUseage;
    @BindView(R.id.et_car_bak)
    EditText etCarbak;
    @BindView(R.id.et_engine_no)
    EditText etEngineNo;
    @BindView(R.id.tv_car_weight)
    TextView tvCarWeightTitle;
    @BindView(R.id.et_car_Weight)
    EditText etCarWeight;

    private String front_id_card_uri, contrary_id_card_uri;
    private Customer data;

    private String mCarDate = "";
    private TimePickerView mCarDatePicker;

    private AlertView mPhotoAlert;
    private int mPhotoStatus;
    private int mCartype = 1;
    private int mUseage = 2;

    @Override
    public int getLayoutResId() {
        return R.layout.manage_into_car_layout;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.manager_message));
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            data = bundle.getParcelable(IntentKey.CUSTOMER);
        }
        initPicker();
        initTransform();
    }

    private void initAlertView() {
        mPhotoAlert = new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CAMERA_OR_LOCAL,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0:
                        photoCamera();
                        break;
                    case 1:
                        photoLocal();
                        break;
                }
            }
        });
    }

    private void photoCamera() {
        switch (mPhotoStatus) {
            case 1://行驶证正面
                Bundle bundle1 = new Bundle();
                bundle1.putInt(IntentKey.FROM, 2);
                ShowActivity.showActivityForResult(AddManagerCarActivity.this, IdCardCameraActivity.class,
                        bundle1, RequestCodeKey.CAR_IDENTIFY_FRONT);
                break;
            case 2:
                //行驶证反面
                Bundle bundle2 = new Bundle();
                bundle2.putInt(IntentKey.FROM, 2);
                ShowActivity.showActivityForResult(AddManagerCarActivity.this, IdCardCameraActivity.class,
                        bundle2, RequestCodeKey.CAR_IDENTIFY_CONTRARY);
                break;
        }
    }


    private void photoLocal() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        try {
            startActivityForResult(Intent.createChooser(intent, "请选择一张图片"),
                    RequestCodeKey.TAKE_PHOTO_LOCAL);
        } catch (Exception e) {
            CommonUtil.showToast(this, "请安装文件管理器");
        }
    }

    private void initPicker() {
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(Constant.YEAR_BEGIN, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(Constant.YEAR_END, 11, 31);
        mCarDatePicker = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                mCarDate = DateUtil.parseDate(date);
                tvCarDate.setText(DateUtil.getDate(date));
            }
        }).setDate(selectedDate)
                .isCyclic(true)
                .setRangDate(startDate, endDate)
                .setTitleText(getString(R.string.regist_date))
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();
    }

    private void initTransform() {
        AllCapTransformationMethod transformationMethod = new AllCapTransformationMethod();
        etCarNumber.setTransformationMethod(transformationMethod);
        etEngineNo.setTransformationMethod(transformationMethod);
        etVin.setTransformationMethod(transformationMethod);
    }

    @Override
    public void addListener() {
        MyOnCheckedChangedListener rgCheckedListener = new MyOnCheckedChangedListener();
        rgCartype.setOnCheckedChangeListener(rgCheckedListener);
        rgUseage.setOnCheckedChangeListener(rgCheckedListener);
    }

    @OnClick({R.id.tv_car_date, R.id.btn_next, R.id.identity_front, R.id.identity_contrary,
            R.id.img_identity_front_clear, R.id.img_identity_contrary_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_car_date://选择车辆注册时间
                if (mCarDatePicker != null) {
                    mCarDatePicker.show();
                }
                break;
            case R.id.btn_next:
                if (front_id_card_uri != null) {
                    data.setD1_photo(front_id_card_uri);
                } else {
                    showToast(getString(R.string.input_car_photo1));
                    return;
                }
                if (contrary_id_card_uri != null) {
                    data.setD2_photo(contrary_id_card_uri);
                } else {
                    showToast(getString(R.string.input_car_photo2));
                    return;
                }
                if (CommonUtil.isEmpty(etCarNumber)) {
                    showToast(getString(R.string.input_car_no));
                } else {
                    data.setPlate_no(getEditString(etCarNumber));
                }
                if (CommonUtil.isEmpty(etVin)) {
                    showToast(getString(R.string.input_car_id));
                    return;
                } else if (etVin.length() < 17) {
                    showToast("车辆识别码的长度不够");
                    return;
                } else {
                    data.setVin(getEditString(etVin));
                }
                if (CommonUtil.isEmpty(tvCarDate)) {
                    showToast(getString(R.string.input_car_date));
                    return;
                } else {
                    data.setCar_register_date(mCarDate);
                }
                if (switchYear.isChecked()) {
                    data.setTransfer_car(1);
                } else {
                    data.setTransfer_car(2);
                }
                if (switchCarNew.isChecked()) {
                    data.setNew_car(1);
                } else {
                    data.setNew_car(2);
                }
                data.setUseage(mUseage);
                data.setCar_type(mCartype);
                switch (mCartype) {
                    case 1:
                        data.setOutput_volume(etCarWeight.getText().toString().trim());
                        break;
                    case 2:
                        data.setCurb_weight(etCarWeight.getText().toString().trim());
                        break;
                }
                data.setEngine_no(etEngineNo.getText().toString().trim());
                data.setCar_bak(etCarbak.getText().toString().trim());
                Bundle bundle = new Bundle();
                bundle.putParcelable(IntentKey.CUSTOMER, data);
                ShowActivity.showActivityForResult(AddManagerCarActivity.this, InsuranceActivity.class, bundle,
                        RequestCodeKey.GO_ADD_CUSTOMER);
                break;
            case R.id.identity_front:
                if(CommonUtil.isEmpty(front_id_card_uri)) {
                    mPhotoStatus = 1;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
                break;
            case R.id.identity_contrary:
                if(CommonUtil.isEmpty(contrary_id_card_uri)) {
                    mPhotoStatus = 2;
                    initAlertView();
                    if (mPhotoAlert != null) {
                        mPhotoAlert.show();
                    }
                }
                break;
            case R.id.img_identity_front_clear:
                identityFrontTv.setVisibility(View.VISIBLE);
                imgIdentityFront.setVisibility(View.GONE);
                imgIdentityFrontClear.setVisibility(View.GONE);
                front_id_card_uri = "";
                break;
            case R.id.img_identity_contrary_clear:
                identityContraryTv.setVisibility(View.VISIBLE);
                imgIdentityContrary.setVisibility(View.GONE);
                imgIndentityContraryClear.setVisibility(View.GONE);
                contrary_id_card_uri = "";
                break;
        }
    }

    private void showFrontImage() {
        identityFrontTv.setVisibility(View.GONE);
        imgIdentityFront.setVisibility(View.VISIBLE);
        imgIdentityFrontClear.setVisibility(View.VISIBLE);
        Glide.with(this).load(front_id_card_uri).into(imgIdentityFront);
    }

    private void showContraryImgae() {
        identityContraryTv.setVisibility(View.GONE);
        imgIdentityContrary.setVisibility(View.VISIBLE);
        imgIndentityContraryClear.setVisibility(View.VISIBLE);
        Glide.with(this).load(contrary_id_card_uri).into(imgIdentityContrary);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case Constant.CAMERA_SUCESS:
                switch (requestCode) {
                    case RequestCodeKey.CAR_IDENTIFY_FRONT:
                        //证件正面
                        if (data != null && data.getData() != null) {
                            front_id_card_uri = data.getData().getPath();
                            XLog.e(front_id_card_uri);
                            showFrontImage();
                        }
                        break;
                    case RequestCodeKey.CAR_IDENTIFY_CONTRARY:
                        //证件反面
                        if (data != null && data.getData() != null) {
                            contrary_id_card_uri = data.getData().getPath();
                            XLog.e(contrary_id_card_uri);
                            showContraryImgae();
                        }
                        break;
                }
                break;
            case RESULT_OK:
                switch (requestCode) {
                    case RequestCodeKey.TAKE_PHOTO_LOCAL:
                        if (data != null && data.getData() != null) {
                            Uri uri = data.getData();
                            String path = CommonUtil.getLocalImagePath(this, uri);
                            XLog.e("path==>" + path);
                            switch (mPhotoStatus) {
                                case 1:
                                    front_id_card_uri = path;
                                    showFrontImage();
                                    break;
                                case 2:
                                    contrary_id_card_uri = path;
                                    showContraryImgae();
                                    break;
                            }
                        }
                        break;
                    case RequestCodeKey.GO_ADD_CUSTOMER:
                        boolean flag = data.getBooleanExtra(IntentKey.SUCCESS, false);
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.SUCCESS, flag);
                        setResult(RESULT_OK, intent);
                        finish();
                        break;
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MyOnCheckedChangedListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkId) {
            switch(radioGroup.getId()) {
                case R.id.car_type_rg:
                    switch (checkId) {
                        case R.id.car_rb:
                            mCartype = 1;
                            tvCarWeightTitle.setText(getString(R.string.output_volume));
                            etCarWeight.setHint(getString(R.string.output_volume_hint));
                            break;
                        case R.id.truck_rb:
                            mCartype = 2;
                            tvCarWeightTitle.setText(getString(R.string.curb_weight));
                            etCarWeight.setText(getString(R.string.curb_weight));
                            break;
                    }
                    break;
                case R.id.policy_usage_rg:
                switch (checkId) {
                    case R.id.policy_operation_rb:
                        mUseage = 1;
                        break;
                    case R.id.policy_operation_not_rb:
                        mUseage = 2;
                        break;
                }
                    break;
            }
        }
    }
}
